﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace WeiXinMessage_4._5
{
    public class SendMsgService
    {


        private static string corpId = "your corpId";
        private static string secretKey = "your secretKey";
        private static AccessTokenHelper _accessTokenHelper = AccessTokenHelper.GetInstance();
        private const string SendMessageApi = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={0}";

        public static void SendTextMssage(string content, string recipients, string agentid)
        {
            //填充消息实体
            Message msg = new Message
            {
                agentid = agentid,
                msgtype = "text",
                safe = "0",
                text = new MsgContent { content = content },
                touser = recipients
            };

            //序列化实体为json
            string json = JsonConvert.SerializeObject(msg,
                new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

            //获取access_token
            string access_token = _accessTokenHelper.GetAccessToken(corpId, secretKey, DateTime.Now);

            //调用消息发送接口
            string xmlString = HttpClientHelper.PostResponse(string.Format(SendMessageApi, access_token), json);
        }
    }

    //消息内容
    public class MsgContent
    {
        public string content { get; set; }
    }


    public class Message
    {
        public string touser { get; set; }

        public string toparty { get; set; }

        public string totag { get; set; }

        public string msgtype { get; set; }

        public string agentid { get; set; }

        //文本消息
        public MsgContent text { get; set; }

        public string safe { get; set; }
    }
}
